import React, { useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, PageContainer } from '@ant-design/pro-components';
import { Button, Tag, Modal, Image, Card, Row, Col, Space, Descriptions, message, Select } from 'antd';
import { EyeOutlined, CheckOutlined, CloseOutlined, UserOutlined } from '@ant-design/icons';
import { getIdentityVerifications, reviewIdentityVerification, getIdentityVerificationDetail } from '@/services/game-platform/api';
import type { GamePlatform } from '@/services/game-platform/typings';

const { Option } = Select;

const IdentityVerificationList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const [selectedRecord, setSelectedRecord] = useState<GamePlatform.IdentityVerification | null>(null);
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [reviewAction, setReviewAction] = useState<'APPROVE' | 'REJECT'>('APPROVE');
  const [rejectReason, setRejectReason] = useState('');
  const [loading, setLoading] = useState(false);

  // 状态颜色映射
  const statusColorMap = {
    'PENDING': 'processing',
    'APPROVED': 'success',
    'REJECTED': 'error',
    'EXPIRED': 'default',
    'NOT_SUBMITTED': 'default',
  } as const;

  // 状态文本映射
  const statusTextMap = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'EXPIRED': '已过期',
    'NOT_SUBMITTED': '未提交',
  } as const;

  const columns: ProColumns<GamePlatform.IdentityVerification>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '用户信息',
      dataIndex: 'username',
      width: 120,
      render: (_, record) => (
        <div>
          <div><UserOutlined /> {record.username}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>
            {record.userNickname || '未设置昵称'}
          </div>
        </div>
      ),
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      width: 100,
      search: false,
    },
    {
      title: '身份证号',
      dataIndex: 'idCardNumber',
      width: 180,
      search: false,
      render: (_, record: GamePlatform.IdentityVerification) => {
        const text = record.idCardNumber;
        if (!text) return '-';
        // 脱敏显示身份证号
        return text.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2');
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_, record: GamePlatform.IdentityVerification) => {
        const status = record.status as keyof typeof statusColorMap;
        return (
          <Tag color={statusColorMap[status] || 'default'}>
            {statusTextMap[status] || status}
          </Tag>
        );
      },
      valueType: 'select',
      valueEnum: {
        PENDING: { text: '待审核', status: 'Processing' },
        APPROVED: { text: '已通过', status: 'Success' },
        REJECTED: { text: '已拒绝', status: 'Error' },
        EXPIRED: { text: '已过期', status: 'Default' },
      },
    },
    {
      title: '提交时间',
      dataIndex: 'submittedAt',
      width: 160,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '审核时间',
      dataIndex: 'reviewedAt',
      width: 160,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '审核人',
      dataIndex: 'reviewedBy',
      width: 100,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          查看详情
        </Button>,
        record.status === 'PENDING' && (
          <Button
            key="approve"
            type="link"
            size="small"
            icon={<CheckOutlined />}
            style={{ color: '#52c41a' }}
            onClick={() => handleReview(record, 'APPROVE')}
          >
            通过
          </Button>
        ),
        record.status === 'PENDING' && (
          <Button
            key="reject"
            type="link"
            size="small"
            icon={<CloseOutlined />}
            style={{ color: '#ff4d4f' }}
            onClick={() => handleReview(record, 'REJECT')}
          >
            拒绝
          </Button>
        ),
      ].filter(Boolean),
    },
  ];

  // 查看详情
  const handleViewDetail = async (record: GamePlatform.IdentityVerification) => {
    try {
      setLoading(true);
      const response = await getIdentityVerificationDetail(record.id);
      if (response.code === 200 && response.data) {
        setSelectedRecord(response.data);
        setDetailModalVisible(true);
      } else {
        message.error(response.message || '获取详情失败');
      }
    } catch (error) {
      message.error('获取详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 审核操作
  const handleReview = (record: GamePlatform.IdentityVerification, action: 'APPROVE' | 'REJECT') => {
    setSelectedRecord(record);
    setReviewAction(action);
    setRejectReason('');
    setReviewModalVisible(true);
  };

  // 确认审核
  const handleConfirmReview = async () => {
    if (!selectedRecord) return;
    
    if (reviewAction === 'REJECT' && !rejectReason.trim()) {
      message.error('请填写拒绝原因');
      return;
    }

    try {
      setLoading(true);
      const response = await reviewIdentityVerification(selectedRecord.id, {
        action: reviewAction,
        rejectReason: reviewAction === 'REJECT' ? rejectReason : undefined,
      });
      
      if (response.code === 200) {
        message.success(response.message || '审核成功');
        setReviewModalVisible(false);
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('审核失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer
      title="实名认证审核"
      subTitle="管理用户实名认证申请"
    >
      <ProTable<GamePlatform.IdentityVerification>
        headerTitle="认证申请列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="refresh"
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
        ]}
        request={async (params) => {
          try {
            const response = await getIdentityVerifications({
              page: (params.current || 1) - 1,
              size: params.pageSize || 20,
              status: params.status as any,
              keyword: params.username,
            });
            
            if (response.code === 200) {
              // 后端返回的是数组，而不是分页对象
              const data = Array.isArray(response.data) ? response.data : [];
              return {
                data: data,
                success: true,
                total: data.length, // 暂时使用数组长度，后端需要支持分页
              };
            }
            return {
              data: [],
              success: false,
              total: 0,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
      />

      {/* 详情模态框 */}
      <Modal
        title="实名认证详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
          selectedRecord?.status === 'PENDING' && (
            <Button
              key="approve"
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => {
                setDetailModalVisible(false);
                handleReview(selectedRecord, 'APPROVE');
              }}
            >
              通过审核
            </Button>
          ),
          selectedRecord?.status === 'PENDING' && (
            <Button
              key="reject"
              danger
              icon={<CloseOutlined />}
              onClick={() => {
                setDetailModalVisible(false);
                handleReview(selectedRecord, 'REJECT');
              }}
            >
              拒绝审核
            </Button>
          ),
        ].filter(Boolean)}
        width={800}
      >
        {selectedRecord && (
          <div>
            <Descriptions title="基本信息" column={2} bordered>
              <Descriptions.Item label="用户名">{selectedRecord.username}</Descriptions.Item>
              <Descriptions.Item label="用户昵称">{selectedRecord.userNickname || '未设置'}</Descriptions.Item>
              <Descriptions.Item label="真实姓名">{selectedRecord.realName}</Descriptions.Item>
              <Descriptions.Item label="身份证号">{selectedRecord.idCardNumber}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={statusColorMap[selectedRecord.status as keyof typeof statusColorMap]}>
                  {statusTextMap[selectedRecord.status as keyof typeof statusTextMap]}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="提交时间">{selectedRecord.submittedAt}</Descriptions.Item>
              {selectedRecord.reviewedAt && (
                <Descriptions.Item label="审核时间">{selectedRecord.reviewedAt}</Descriptions.Item>
              )}
              {selectedRecord.reviewedBy && (
                <Descriptions.Item label="审核人">{selectedRecord.reviewedBy}</Descriptions.Item>
              )}
              {selectedRecord.rejectReason && (
                <Descriptions.Item label="拒绝原因" span={2}>{selectedRecord.rejectReason}</Descriptions.Item>
              )}
            </Descriptions>

            <Card title="身份证照片" style={{ marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ marginBottom: 8 }}>身份证正面</div>
                    <Image
                      width="100%"
                      src={selectedRecord.frontImageUrl}
                      placeholder={<div style={{ height: 150, background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>身份证正面</div>}
                    />
                  </div>
                </Col>
                <Col span={8}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ marginBottom: 8 }}>身份证反面</div>
                    <Image
                      width="100%"
                      src={selectedRecord.backImageUrl}
                      placeholder={<div style={{ height: 150, background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>身份证反面</div>}
                    />
                  </div>
                </Col>
                <Col span={8}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ marginBottom: 8 }}>手持身份证</div>
                    <Image
                      width="100%"
                      src={selectedRecord.handheldImageUrl}
                      placeholder={<div style={{ height: 150, background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>手持身份证</div>}
                    />
                  </div>
                </Col>
              </Row>
            </Card>
          </div>
        )}
      </Modal>

      {/* 审核模态框 */}
      <Modal
        title={`${reviewAction === 'APPROVE' ? '通过' : '拒绝'}审核`}
        open={reviewModalVisible}
        onCancel={() => setReviewModalVisible(false)}
        onOk={handleConfirmReview}
        confirmLoading={loading}
      >
        {selectedRecord && (
          <div>
            <p>确定要{reviewAction === 'APPROVE' ? '通过' : '拒绝'}用户 <strong>{selectedRecord.username}</strong> 的实名认证申请吗？</p>
            {reviewAction === 'REJECT' && (
              <div style={{ marginTop: 16 }}>
                <label>拒绝原因：</label>
                <Select
                  style={{ width: '100%', marginTop: 8 }}
                  placeholder="请选择拒绝原因"
                  value={rejectReason}
                  onChange={setRejectReason}
                  allowClear
                >
                  <Option value="身份证照片不清晰">身份证照片不清晰</Option>
                  <Option value="身份证信息与填写信息不符">身份证信息与填写信息不符</Option>
                  <Option value="手持身份证照片不规范">手持身份证照片不规范</Option>
                  <Option value="身份证照片疑似伪造">身份证照片疑似伪造</Option>
                  <Option value="提供的信息不完整">提供的信息不完整</Option>
                  <Option value="其他原因">其他原因</Option>
                </Select>
              </div>
            )}
          </div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default IdentityVerificationList;
